package com.humh.makeplanning;

import java.time.LocalDateTime;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Set;
import lombok.NonNull;

// 物料工人
public class MaterialWorker {

  protected static final int PROCESSING_TIME = 2;  //加工部件的时间，单位：小时

  private Set<String> taskIdSet; // 已完成制定任务计划集合
  private volatile boolean isBusy; // 是否正在加工  true:正在加工，false:空闲

  // 任务排期队列 ,在添加新任务时，从此队列的队尾取出TaskScheduling对象，即可获得最后一次任务的完成时间
  private ArrayDeque<TaskScheduling> taskSchedulingQueue;

  private LocalDateTime scheduleStartTime; // 新任务计划开始时间

  public MaterialWorker() {
    this.isBusy = false;
    this.taskIdSet = new HashSet<>();
    this.taskSchedulingQueue = new ArrayDeque<>();
  }

  /**
   * 制定工作计划
   * @param task
   */
  public void developWorkPlan(@NonNull Task task) {
    if (isScheduled(task.getTaskId())) {
      return  ;
    }
    this.isBusy = true; // 开始制定任务计划时， 则置为繁忙状态

    TaskScheduling taskSchedulingTmp = taskSchedulingQueue.peekLast();
    if (taskSchedulingTmp == null) {
      scheduleStartTime = LocalDateTime.now();
    } else {
      scheduleStartTime = taskSchedulingTmp.getEndTime();
    }

    TaskScheduling taskScheduling = new TaskScheduling(task, scheduleStartTime);
    taskSchedulingQueue.addLast(taskScheduling);
    taskIdSet.add(task.getTaskId());
    this.isBusy = false; // 完成任务计划分配后，则置为空闲状态
  }

  /**
   * 获取最后一个任务完成时间
   */
  public LocalDateTime getTheLastTimeToComplete() {
    TaskScheduling taskSchedulingTmp = taskSchedulingQueue.peekLast();
    if (taskSchedulingTmp == null) {
      return LocalDateTime.now();
    } else {
      return taskSchedulingTmp.getEndTime();
    }
  }

  /**
   * 获取任务排期计划
   */
  public ArrayDeque getTaskPlan() {

    ArrayDeque<TaskScheduling> taskSchedulingQueueClone=new ArrayDeque<>();
    for (TaskScheduling taskScheduling : taskSchedulingQueue){
      taskSchedulingQueueClone.add(taskScheduling.clone());
    }

    return taskSchedulingQueueClone;
  }

  /**
   * 判断任务是否已经排期
   *
   * @param taskId
   * @return true : 已经排程
   */
  private boolean isScheduled(String taskId) {
    if (taskId !=null && !"".equals(taskId)  && taskIdSet.contains(taskId)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 清空任务计划
   */
  public void clearTaskPlan() {
    taskSchedulingQueue.clear();
    taskIdSet.clear();
    scheduleStartTime=null;
  }

  public static void main(String[] args) {
    MaterialWorker materialWorker = new MaterialWorker();
    Task task1 = new Task(1L, "task1");

    materialWorker.developWorkPlan(task1);
    ArrayDeque taskPlan = materialWorker.getTaskPlan();
    System.out.println();
  }


}
